package com.lzl.servicedriveruser.service;

import com.lzl.constant.BindDriverCarConstant;
import com.lzl.constant.CommonStatusEnum;
import com.lzl.dto.DriverCarBindingRelationship;
import com.lzl.responese.ResponseResult;
import com.lzl.servicedriveruser.mapper.DriverCarBindingRelationshipMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzl
 * @since 2022-09-05
 */
@Service
public class DriverCarBindingRelationshipServiceImpl {

    @Autowired
    DriverCarBindingRelationshipMapper driverCarBindingRelationshipMapper;

    public ResponseResult bindDriverCar(DriverCarBindingRelationship driverCarBindingRelationship) {
        LocalDateTime now = LocalDateTime.now();
        driverCarBindingRelationship.setBindingTime(now);
        driverCarBindingRelationship.setBindState(BindDriverCarConstant.BINDING);
        driverCarBindingRelationshipMapper.insert(driverCarBindingRelationship);
        return ResponseResult.success("");

    }

    public ResponseResult unBindDriverCar(DriverCarBindingRelationship driverCarBindingRelationship) {
        HashMap<String,Object> map = new HashMap<>();
        map.put("driver_id",driverCarBindingRelationship.getDriverId());
        map.put("car_id",driverCarBindingRelationship.getCarId());
        List<DriverCarBindingRelationship> driverCarBindingRelationships = driverCarBindingRelationshipMapper.selectByMap(map);
        if(driverCarBindingRelationships == null || driverCarBindingRelationships.isEmpty()){
            return ResponseResult.fail(CommonStatusEnum.DRIVER_CAR_ERROR.getCode(),CommonStatusEnum.DRIVER_CAR_ERROR.getValue());
        }

        DriverCarBindingRelationship unDriverCarBinding = driverCarBindingRelationships.get(0);
        if(unDriverCarBinding.getBindState() == BindDriverCarConstant.UNBINDING){
            return ResponseResult.fail(CommonStatusEnum.DRIVER_CAR_STATE.getCode(),CommonStatusEnum.DRIVER_CAR_STATE.getValue());
        }
        unDriverCarBinding.setBindState(BindDriverCarConstant.UNBINDING);
        LocalDateTime now = LocalDateTime.now();
        unDriverCarBinding.setUnBindingTime(now);
        driverCarBindingRelationshipMapper.updateById(unDriverCarBinding);
        return ResponseResult.success("");

    }
}
